package com.itheima.ydd.controller;


import com.itheima.ydd.common.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传下载
 */
@RestController
//@RequestMapping("/admin/common")
@Slf4j
public class CommonController {
    @Value("${ydd.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/common/upload")
    public ResultData upload(MultipartFile file, String type) {
        //file是一个临时文件,存放在temp文件夹里,需要转存到指定位置,否则本次请求完成临时文件会删除
        log.info(file.toString());
        //原始上传文件名
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //改用UUID防止文件重名导致文件覆盖
        String fileName = UUID.randomUUID().toString() + substring;

        //获取当前年月日
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String savePath = basePath + date + "/" + fileName;
        //创建图片存放目录
        File dir = new File(basePath + date);
        if (!dir.exists()) {
            dir.mkdir();
        }
        try {
            //临时文件转存到指定位置
            file.transferTo(new File(savePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取当前年月日
        String name = originalFilename;
        String mime = type + "/" + (substring.split("\\.")[1]);
        long size = file.getSize();

        Map map = new HashMap();
        map.put("savePath", savePath);//储存路径/日期/文件名
        map.put("name", name);//原始文件名
        map.put("mime", mime);//文件类型/后缀名
        map.put("size", size);//文件大小
        return ResultData.ok("",map);

    }

    /**
     * 下载图片
     * @param response
     * @param date
     * @param name
     */
    @GetMapping("undefinedd:/Software/idea/IdeaProjects/ydd/src/main/resources/static/images/{date}/{name}")
    public void download(HttpServletResponse response, @PathVariable(value ="date") String date, @PathVariable(value ="name") String name) {
        try {
            //输入流,读取文件
            FileInputStream fis = new FileInputStream(new File(basePath + date + "/" + name));
            //输出流,传回文件到浏览器
            ServletOutputStream sos = response.getOutputStream();
            //response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                sos.write(bytes, 0, len);
                sos.flush();
            }
            sos.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
